package com.hzeport.bgs22emduty.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctc.wstx.util.StringUtil;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ScreenDutyLogDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import com.hzeport.bgs22emduty.service.DutySignInfoService;
import com.hzeport.bgs22emduty.service.SecurityLogService;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyLogSaveVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.utils.IpUtils;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.outbound.db.ScreenDutyLogRepositoryImpl;
import com.hzeport.bgs22emduty.service.ScreenDutyLogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class    ScreenDutyLogServiceImpl extends BaseServiceImpl<ScreenDutyLogRepositoryImpl, ScreenDutyLog> implements ScreenDutyLogService {

    @Resource
    private ScreenDutyLogRepository screenDutyLogRepository;

    @Resource
    private LoginCompoentService loginCompoentService;

    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptInfoService baseDeptInfoService;
    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private DutySignInfoRepository dutySignInfoRepository;
    @Resource
    private DutySignInfoService dutySignInfoService;
    @Resource
    private  ScreenMapsRepository screenMapsRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private SecurityLogService securityLogService;

    @Override
    public Object page(ScreenDutyLogDTO dto) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenDutyLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(userInfoDetailVO.getCustomscode()),ScreenDutyLog::getCustomId,userInfoDetailVO.getCustomscode());
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyWord()),ScreenDutyLog::getTitle,dto.getKeyWord());
        if (StringUtils.isNotBlank(dto.getStartDate())){
            LocalDateTime startLocalDateTime = LocalDate.parse(dto.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            queryWrapper.ge(ScreenDutyLog::getCreateTime,startLocalDateTime);
        }
        if (StringUtils.isNotBlank(dto.getEndDate())){
            LocalDateTime endLocalDateTime = LocalDate.parse(dto.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().plusDays(1);
            queryWrapper.le(ScreenDutyLog::getCreateTime,endLocalDateTime);
        }
        if (StringUtils.isNotBlank(dto.getTitle())){
            queryWrapper.like(ScreenDutyLog::getTitle,dto.getTitle());
        }
        queryWrapper.orderByDesc(ScreenDutyLog::getCreateTime);
        Page<ScreenDutyLog> page = screenDutyLogRepository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult savels(ScreenDutyLogSaveVO screenDutyLogSaveVO, HttpServletRequest request ) throws Exception {
        if (StringUtils.isEmpty(screenDutyLogSaveVO.getTitle())){
            return BaseResult.failed("日志标题不能不能为空");
        }
        if (screenDutyLogSaveVO.getFileCount()==null){
            return BaseResult.failed(" 文件数量不能为空");
        }
        if (screenDutyLogSaveVO.getPhoneCount()==null){
            return BaseResult.failed("电话数量不能为空");
        }
        if (screenDutyLogSaveVO.getDistributeCount()==null){
            return BaseResult.failed("通知数量不能为空");
        }
        if (screenDutyLogSaveVO.getMessageCount()==null){
            return BaseResult.failed("信息数量不能为空");
        }
        if (screenDutyLogSaveVO.getFileCount()!=0) {
            if (screenDutyLogSaveVO.getFileDetail()==null){
                return BaseResult.failed("文件数量不为0时，需要填写详情");
            }
        }
        if (screenDutyLogSaveVO.getPhoneCount()!=0) {
            if (screenDutyLogSaveVO.getPhoneDetail()==null){
                return BaseResult.failed("电话数量不为0时，需要填写详情");
            }
        }
        if (screenDutyLogSaveVO.getDistributeCount()!=0) {
            if (screenDutyLogSaveVO.getDistributeDetail()==null){
                return BaseResult.failed("通知数量不为0时，需要填写详情");
            }
        }
        if (screenDutyLogSaveVO.getMessageCount()!=0) {
            if (screenDutyLogSaveVO.getMessageDetail()==null){
                return BaseResult.failed("信息数量不为0时，需要填写详情");
            }
        }
            ScreenDutyLog screenDutyLog = new ScreenDutyLog();
        BeanUtils.copyProperties(screenDutyLogSaveVO, screenDutyLog);
        if (!StringUtils.isEmpty(screenDutyLogSaveVO.getPersonNo())) {
            screenDutyLog.setCreatePerson(screenDutyLogSaveVO.getPersonNo());
            BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, screenDutyLogSaveVO.getPersonNo()), false);
            if (basePersonInfo != null) {
//                String baseDeptId=baseDeptInfoService.getCustomIdByDeptId(basePersonInfo.getDeptId());
//                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(baseDeptId);
//                BaseDeptInfo baseDeptInfo=basePersonInfoRepository.getById()
//                screenDutyLog.setCustomId(baseDeptInfo.getId());
//                screenDutyLog.setCustomName(baseDeptInfo.getDeptNa/me());
            }
        }
        List<ScreenDutyLog> old = null;
        if (!StringUtils.isEmpty(screenDutyLogSaveVO.getPersonNo())){
            old = screenDutyLogRepository.list(new LambdaQueryWrapper<ScreenDutyLog>()
                    .eq(ScreenDutyLog::getCreatePerson, screenDutyLogSaveVO.getPersonNo())
                    .ge(ScreenDutyLog::getCreateTime, LocalDate.now().atStartOfDay()));
        }
        if(StringUtils.isEmpty(screenDutyLog.getId())){
//            screenDutyLog.setStartTime(!StringUtils.isEmpty(screenDutyLogSaveVO.getStartTime())?LocalDateTime.parse(screenDutyLogSaveVO.getStartTime()):null);
//            screenDutyLog.setEndTime(!StringUtils.isEmpty(screenDutyLogSaveVO.getEndTime())?LocalDateTime.parse(screenDutyLogSaveVO.getEndTime()):null);
            screenDutyLog.setCreateTime(LocalDateTime.now());
            screenDutyLog.setUpdateTime(LocalDateTime.now());
            if (StringUtils.isEmpty(screenDutyLogSaveVO.getPersonNo())){
                throw new Exception("日志上传时，应当提供日志编写人工号!");
            }else {
                List<DutyScheduleInfo>  dutyScheduleInfos=dutyScheduleInfoRepository.list(new LambdaQueryWrapper<DutyScheduleInfo>()
//                        .le(DutyScheduleInfo::getDDay,LocalDate.now()).ge(DutyScheduleInfo::getDDay,LocalDate.now().minusDays(5L))
                        .in(DutyScheduleInfo::getDUserjob,"科员","科领导")
                        .eq(DutyScheduleInfo::getDUserno,screenDutyLogSaveVO.getPersonNo())
                        .orderByDesc(DutyScheduleInfo::getDStartDateTime));
                if (!CollectionUtils.isEmpty(dutyScheduleInfos)){
                    LocalDateTime now=LocalDateTime.now();
                    DutyScheduleInfo targetScheduleInfo=dutySignInfoService.getSignInTaragetScheduleInfo(dutyScheduleInfos,now);
//                    DutySignInfo dutySignInfo=dutySignInfoRepository.getOne(new LambdaQueryWrapper<DutySignInfo>()
//                    .eq(DutySignInfo::getDId,targetScheduleInfo.getId()),false);
//                    if (dutySignInfo!=null) {
                        screenDutyLog.setRid(targetScheduleInfo.getId());
//                    }
                }
            }
            screenDutyLog.setCreateBy(screenDutyLogSaveVO.getPersonNo());
            screenDutyLog.setUpdateBy(screenDutyLogSaveVO.getPersonNo());
            screenDutyLog.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyLog.setChangeFlag(1);
            screenDutyLogRepository.save(screenDutyLog);
            if (!CollectionUtils.isEmpty(old)){
                screenDutyLogRepository.removeByIds(old.stream().map(i->i.getId()).collect(Collectors.toList()));
            }
        }else {
            ScreenDutyLog byId = screenDutyLogRepository.getById(screenDutyLog.getId());
//            screenDutyLog.setStartTime(!StringUtils.isEmpty(screenDutyLogSaveVO.getStartTime())?LocalDateTime.parse(screenDutyLogSaveVO.getStartTime()):null);
//            screenDutyLog.setEndTime(!StringUtils.isEmpty(screenDutyLogSaveVO.getEndTime())?LocalDateTime.parse(screenDutyLogSaveVO.getEndTime()):null);
            if (byId != null){
                screenDutyLog.setRecVersion(byId.getRecVersion());
            }
            screenDutyLog.setUpdateTime(LocalDateTime.now());
            screenDutyLog.setUpdateBy(screenDutyLogSaveVO.getPersonNo());
            screenDutyLog.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyLog.setChangeFlag(1);
            screenDutyLogRepository.updateById(screenDutyLog);
        }

//        ScreenMaps screenMaps = screenMapsRepository.getById(screenDutyLog.getCustomId());
//        screenMaps.setStateFlag(screenDutyLogSaveVO.getNoticeType());
//        screenMaps.setWarnCont(screenDutyLogSaveVO.getMainBody());
//        if("0".equals(screenDutyLogSaveVO.getNoticeType()) || "1".equals(screenDutyLogSaveVO.getNoticeType())){
//            screenMaps.setWarn("1");
//        }else {
//            screenMaps.setWarn("0");
//        }
//        screenMaps.setStartTime(!StringUtils.isEmpty(screenDutyLogSaveVO.getStartTime())?LocalDateTime.parse(screenDutyLogSaveVO.getStartTime()):null);
//        screenMaps.setEndTime(!StringUtils.isEmpty(screenDutyLogSaveVO.getEndTime())?LocalDateTime.parse(screenDutyLogSaveVO.getEndTime()):null);
//        screenMapsRepository.updateById(screenMaps);
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy(screenDutyLogSaveVO.getCreatePerson());
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress( IpUtils.getIpAddr(request));
        operateLog.setSDescription( JSON.toJSONString( screenDutyLogSaveVO ) );
        operateLog.setSModule("TBSQLS");
        operateLog.setSTitle("qrtb");
        securityLogService.save(operateLog);
        return BaseResult.ok(screenDutyLog,"保存成功");
    }

    @Override
    public Object update(ScreenDutyLog screenDutyLog) {
        ScreenDutyLog screenDutyLogUpdate = new ScreenDutyLog();
        BeanUtils.copyProperties(screenDutyLog,screenDutyLogUpdate);
        if (StringUtils.isEmpty(screenDutyLog.getId())){
            ScreenDutyLog byId = screenDutyLogRepository.getById(screenDutyLog.getId());
            if (byId != null){
                screenDutyLogUpdate.setRecVersion(byId.getRecVersion());
            }
        }
        screenDutyLogRepository.updateById(screenDutyLogUpdate);
        return screenDutyLogUpdate;
    }

    @Override
    public BaseResult getOne(String id, HttpServletRequest request ) {
        return BaseResult.ok(screenDutyLogRepository.getById(id));
    }
}
